package com.pcbly.web.components.utils.excel;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFWorkbook; 

import com.pcbly.web.bean.report.JXLSReportInfo;
import com.pcbly.web.servlet.POIProcessor;

public class JXLSReportServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3019303355779046283L;

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		JXLSReportInfo info = (JXLSReportInfo) request
				.getAttribute("reportInfo");
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment; filename="
				+ info.getFileName());
		System.out.println(getClass());
		XLSTransformer transformer = new XLSTransformer();
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(info
					.getTemplate()), 25000); 
			
			HSSFWorkbook workbook =transformer.transformXLS(in, info.getContext()); 
			// post process workbook 
			POIProcessor processor = (POIProcessor) request.getAttribute("poiPreProcessor");
			if (processor != null) {
				workbook = processor.process(workbook);
			}
			// write to buffer
			ByteArrayOutputStream buf = new ByteArrayOutputStream(40000);
			workbook.write(buf);
			// write to response
			in.close();
			ServletOutputStream out = response.getOutputStream();
			out.write(buf.toByteArray());
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
